<?php
namespace app\workers\controller;

use app\model\ConfigModel;
use app\model\WorkersTaskModel;
use app\model\WorkersTaskRatingScaleModel;
use app\model\WorkersTaskUserModel;
use app\admin\service\RatingScaleService;
use app\model\WorkersTaskUserResultContinuityModel;
use app\model\WorkersTaskUserResultModel;
use app\workers\service\RatingScaleService as WorkersRatingScaleService;
use app\model\RatingScaleModel;

class Task extends BaseController
{
    /**
     * 获取系统设置参数
     * @return bool|string
     */
    public function getConfig(): bool|string
    {
        $param = $this->request->param();
        try {
            $this->validate($param, [
                'key|键'  =>  'require',
            ]);
            $ConfigModel = new ConfigModel();
            $data = $ConfigModel->where([
                'unit_id' => $this->userData['unit_id'],
                'key' => $param['key']
            ])->value('value')??'';
            $data = json_decode($data,true);
            return success($data);
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }

    /**
     * 存储临时答案
     * @return bool|string
     */
    public function StoreTemporaryAnswers(): bool|string
    {
        try {
            $task_id = $this->request->param('task_id');
            $rating_scale_id = $this->request->param('rating_scale_id');
            $value = $this->request->param('value');
            $key = 'workers_task_id'.$task_id.'rating_scale_id'.$rating_scale_id.'uid'.$this->userData['id'];
            cache($key,$value);
            return success();
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }

    /**
     * 获取临时答案
     * @return bool|string
     */
    public function ObtainTemporaryAnswers(): bool|string
    {
        try {
            $task_id = $this->request->param('task_id');
            $rating_scale_id = $this->request->param('rating_scale_id');
            $key = 'workers_task_id'.$task_id.'rating_scale_id'.$rating_scale_id.'uid'.$this->userData['id'];
            return success(cache($key));
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }

    /**
     * 任务测评列表
     * @return bool|string
     */
    public function taskList(): bool|string
    {
        try {
            $param = $this->request->param();
            $where = [];
            $TaskUserModel = new WorkersTaskUserModel();
            $taskIds = $TaskUserModel->where([
                ['uid','=',$this->userData['id']],
                ['is_finish','=',0]
            ])->column('task_id');
            $taskIds = array_unique($taskIds);
            if (count($taskIds)) {
                $where[] = ['id','in',$taskIds];
            }else{
                $where[] = ['id','=',-1];
            }
            $where[] = ['unit_id','=',$this->userData['unit_id']];
            $where[] = ['status','=',2];
            $TaskModel = new WorkersTaskModel();
            $data = $TaskModel->where($where)
                ->with([
                    'userName' => function($query){
                        $query->with(['roleName']);
                    }
                ])
                ->order('id desc')->paginate($param['pageSize'])->toArray();
            return success($data);
        } catch (\Exception $e) {
            return error($e->getMessage(),$e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile()
            ]);
        }
    }


    /**
     * 获取任务量表名称列表
     * @return false|string
     */
    public function getTaskRatingScaleNameList(): bool|string
    {
        try {
            $task_id = $this->request->param('task_id');
            $TaskRatingScaleModel = new WorkersTaskRatingScaleModel();
            $data = $TaskRatingScaleModel->where('task_id','=',$task_id)
                ->with(['ratingScale'])->select()->toArray();
            return success($data);
        } catch (\Exception $e) {
            return error($e->getMessage(),$e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile()
            ]);
        }
    }

    /**
     * 获取任务量表列表
     * @return false|string
     */
    public function getTaskRatingScaleList(): bool|string
    {
        try {
            $task_id = $this->request->param('task_id');
            $where = [];
            $where[] = ['task_id','=',$task_id];
            $where[] = ['uid','=',$this->userData['id']];
            $TaskUserModel = new WorkersTaskUserModel();
            $data = $TaskUserModel->where($where)
                ->with([
                    'ratingScale'
                ])->select()->toArray();
            return success($data);
        } catch (\Exception $e){
            return error($e->getMessage(),$e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile()
            ]);
        }
    }

    /**
     * 获取量表详情（通过任务用户表id获取）
     * @return false|string
     */
    public function getTaskRatingScaleInfo(): bool|string
    {
        try {
            $id = $this->request->param('id');
            $TaskUserModel = new WorkersTaskUserModel();
            $info = $TaskUserModel->where('id','=',$id)
                ->with([
                    'ratingScale' => function($query){
                        $query->with(['ratingScaleTypeName']);
                    },
                    'task' => function ($query) {
                        $query->with(['userName']);
                    }
                ])->find();
            $RatingScaleService = new RatingScaleService($this->app);
            $question = $RatingScaleService->GetQuestion($info['rating_scale_id']);
            return success([
                'question' => $question,
                'info' => $info
            ]);
        } catch (\Exception $e){
            return error($e->getMessage(),$e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile()
            ]);
        }
    }

    /**
     * 获取量表详情（通过量表id获取）
     * @return bool|string
     */
    public function getRatingScaleInfo(): bool|string
    {
        try {
            $id = $this->request->param('id');
            $RatingScaleModel = new RatingScaleModel();
            $info = $RatingScaleModel->field('id,type_id,name')->with([
                'ratingScaleTypeName'
            ])->find($id);
            $RatingScaleService = new RatingScaleService($this->app);
            $question = $RatingScaleService->GetQuestion($id);
            return success([
                'question' => $question,
                'info' => $info
            ]);
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }

    /**
     * 提交任务测评结果
     * @return false|string
     */
    public function submitTaskEvaluationResults(): bool|string
    {
        $TaskUserModel = new WorkersTaskUserModel();
        $TaskUserModel->startTrans();
        try {
            $param = $this->request->param();
            $this->validate($param,[
                'task_id|任务ID' =>  'require',
                'task_user_id|用户任务表ID' =>  'require',
                'rating_scale_id|量表ID' =>  'require',
                'question_answer|用户填写的答案' =>  'require',
                'finish_used_time|用户完成用时' =>  'require',
            ]);
            //不可重复提交
            $TaskUserInfo = $TaskUserModel->where('id','=',$param['task_user_id'])->field('id,uid,is_finish')->find();
            if (!$TaskUserInfo || $TaskUserInfo['uid'] != $this->userData['id']) throw new \Exception('参数错误！');
            if ($TaskUserInfo['is_finish'] > 0) throw new \Exception('不可重复提交！');
            $RatingScaleService = new WorkersRatingScaleService($this->app);
            if (!$RatingScaleService->generateReport([
                'unit_id' => $this->userData['unit_id'],//答题用户ID
                'uid' => $this->userData['id'],//答题用户ID
                'task_id' => $param['task_id'],//任务ID
                'task_user_id' => $param['task_user_id'],//用户任务表ID
                'rating_scale_id' => $param['rating_scale_id'],//量表ID
                'userAnswer' => $param['question_answer'],//用户填写的答案
                'finish_used_time' => $param['finish_used_time'],//用户完成用时
            ],1))
                throw new \Exception($RatingScaleService->message);
            $TaskUserModel->commit();
            return success([
                'result_id' => $RatingScaleService->ResultId,
                'data' => $RatingScaleService->resultData,
                'is_valid' => $RatingScaleService->is_valid
            ],'提交成功！');
        } catch (\Exception $e) {
            $TaskUserModel->rollback();
            return error($e->getMessage(), $e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }

    /**
     * 提交任务连续测评结果
     * @return false|string
     */
    public function submitTaskContinuousEvaluation(): bool|string
    {
        $TaskUserResultContinuityModel = new WorkersTaskUserResultContinuityModel();
        $TaskUserResultContinuityModel->startTrans();
        $param = $this->request->param();
        try {
            $this->validate($param,[
                'task_id|任务ID' =>  'require',
                'task_user_id|用户任务表ID' =>  'require',
                'rating_scale_id|量表ID' =>  'require',
                'question_answer|用户填写的答案' =>  'require',
                'finish_used_time|用户完成用时' =>  'require',
            ]);
            //不可重复提交
            $is_finish = $TaskUserResultContinuityModel->where([
                'task_user_id' => $param['task_user_id'],
                'rating_scale_id' => $param['rating_scale_id'],
            ])->value('id');
            if ($is_finish) throw new \Exception('不可重复提交！');
            $RatingScaleService = new WorkersRatingScaleService($this->app);
            if (!$RatingScaleService->generateReport([
                'unit_id' => $this->userData['unit_id'],//答题用户ID
                'uid' => $this->userData['id'],//答题用户ID
                'task_id' => $param['task_id'],//任务ID
                'task_user_id' => $param['task_user_id'],//用户任务表ID
                'rating_scale_id' => $param['rating_scale_id'],//量表ID
                'userAnswer' => $param['question_answer'],//用户填写的答案
                'finish_used_time' => $param['finish_used_time'],//用户完成用时
            ],2))
                throw new \Exception($RatingScaleService->message);
            $TaskUserResultContinuityModel->commit();
            return success([
                'result_id' => $RatingScaleService->ResultId,
                'is_valid' => $RatingScaleService->is_valid
            ],'提交成功！');
        } catch (\Exception $e) {
            $TaskUserResultContinuityModel->rollback();
            return error($e->getMessage(), $e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }


    /**
     * 任务测评报告详情
     * @return bool|string
     */
    public function TaskEvaluationReport(): bool|string
    {
        try {
            $id = $this->request->param('id');
            $TaskUserResultModel = new WorkersTaskUserResultModel();
            $info = $TaskUserResultModel->with([
                'RatingScale' => function ($query) {
                    $query->with(['ratingScaleTypeName']);
                },
                'user',
                'RatingScaleFactorWarningModel' => function ($query) {
                    $query->with(['factorName']);
                },
                'TaskFactorScore' => function ($query) {
                    $query->with([
                        'RatingScaleFactor' => function ($query) {
                            $query->with(['RatingScaleFactorLevel']);
                        },
                        'RatingScaleFactorLevel'
                    ]);
                }
            ])->find($id);
            return success($info);
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }

    /**
     * 连续测评结果详情
     * @return bool|string
     */
    public function ContinuousEvaluationResultsInfo(): bool|string
    {
        try {
            $id = $this->request->param('id');
            $TaskUserResultContinuityModel = new WorkersTaskUserResultContinuityModel();
            $data = $TaskUserResultContinuityModel->field('id,rating_scale_id,uid,answer_role,total_score,finish_used_time,is_warning,warning_id,is_follow,is_explain,result_read_auth,time,evaluation_fee,interpretation_fee')
                ->with([
                    'RatingScale' => function ($query) {
                        $query->with(['ratingScaleTypeName']);
                    },
                    'user',
                    'RatingScaleFactorWarningModel' => function ($query) {
                        $query->with(['factorName']);
                    },
                    'TaskFactorScoreContinuity' => function ($query) {
                        $query->with(['RatingScaleFactor', 'RatingScaleFactorLevel']);
                    }
                ])->find($id);
            return success($data);
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }
}